#lang r5rs
(define multiinsertLR
  (lambda (new oldL oldR lat)
    (cond
      ((null? lat) '())
      ((eq? (car lat) oldL)
       (cons new
             (cons oldL
                   (multiinsertLR new oldL oldR (cdr lat)))))
      ((eq? (car lat) oldR)
       (cons oldR
             (cons new
                   (multiinsertLR new oldL oldR (cdr lat)))))
      (else
        (cons (car lat)
              (multiinsertLR new oldL oldR (cdr lat)))))))

(define (multiinsertLR&co new oldL oldR lat col)
  (if (null? lat)
    (col '() 0 0)
    (let ((head (car lat))
          (tail (cdr lat)))
      (cond
        ((eq? head oldL)
         (multiinsertLR&co new oldL oldR tail
                           (lambda (newlat L R)
                             (col (cons new (cons oldL newlat))
                                  (+ 1 L) R))))
        ((eq? head oldR)
         (multiinsertLR&co new oldL oldR tail
                           (lambda (newlat L R)
                             (col (cons oldR (cons new newlat))
                                  L (+ 1 R)))))
        (else
          (multiinsertLR&co new oldL oldR tail
                            (lambda (newlat L R)
                              (col (cons head newlat) L R))))))))


